package com.wcq.studentbackend.controller;

import com.wcq.studentbackend.dto.GradeDTO;
import com.wcq.studentbackend.dto.GradeRequestDTO;
import com.wcq.studentbackend.dto.GradeStatsResponseDTO;
import com.wcq.studentbackend.service.GradeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections; // For creating a simple error map
import java.util.List;
import java.util.Map; // For creating a simple error map
// import javax.validation.Valid;
@Slf4j
@Api(value = "成绩管理")
@RestController
@RequestMapping("/api/grades/admin") // 注意基础路径
public class GradeController {

    private final GradeService gradeService;

    @Autowired
    public GradeController(GradeService gradeService) {
        this.gradeService = gradeService;
    }

    @GetMapping
    @ApiOperation(value = "获取所有成绩信息接口")
    public ResponseEntity<List<GradeDTO>> getAllGrades() {
        // 这里可以根据前端是否传来筛选参数，调用不同的Service方法
        // 为简单起见，先调用获取全部详情的方法
        log.info("Getting all grades with details.");
        List<GradeDTO> grades = gradeService.getAllGradesWithDetails();
        return ResponseEntity.ok(grades);
    }
    
    @GetMapping("/{id}")
    @ApiOperation(value = "获取成绩详细信息接口")
    public ResponseEntity<GradeDTO> getGradeById(@PathVariable Long id) {
        log.info("Getting grade with details by ID: {}", id);
        GradeDTO gradeDTO = gradeService.getGradeWithDetailsById(id);
        if (gradeDTO != null) {
            return ResponseEntity.ok(gradeDTO);
        }
        return ResponseEntity.notFound().build();
    }

    @PostMapping
    @ApiOperation(value = "创建成绩接口")
    public ResponseEntity<?> createGrade(@RequestBody GradeRequestDTO gradeRequestDTO) {
        log.info("Creating grade: {}", gradeRequestDTO);
        try {
            GradeDTO createdGrade = gradeService.createGrade(gradeRequestDTO);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdGrade);
        } catch (IllegalArgumentException e) {
            // 返回包含具体错误信息的JSON对象
            Map<String, String> errorResponse = Collections.singletonMap("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
        } catch (Exception e) { 
            // 其他通用异常
            Map<String, String> errorResponse = Collections.singletonMap("error", "创建成绩时发生未知错误。");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "更新成绩接口")
    public ResponseEntity<?> updateGrade(@PathVariable Long id, @RequestBody GradeRequestDTO gradeRequestDTO) {
        log.info("Updating grade with ID: {}", id);
        try {
            GradeDTO updatedGrade = gradeService.updateGrade(id, gradeRequestDTO);
            if (updatedGrade != null) {
                return ResponseEntity.ok(updatedGrade);
            }
            // 如果 service 层返回 null 代表资源未找到 (例如ID对应的成绩不存在)
            Map<String, String> errorResponse = Collections.singletonMap("error", "未找到要更新的成绩记录，ID: " + id);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
        } catch (IllegalArgumentException e) {
            Map<String, String> errorResponse = Collections.singletonMap("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
        } catch (Exception e) {
            Map<String, String> errorResponse = Collections.singletonMap("error", "更新成绩时发生未知错误。");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除成绩接口")
    public ResponseEntity<Void> deleteGrade(@PathVariable Long id) {
        log.info("Deleting grade with ID: {}", id);
        boolean deleted = gradeService.deleteGrade(id);
        if (deleted) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/search")
    @ApiOperation(value = "搜索成绩接口")
    public ResponseEntity<List<GradeDTO>> searchGrades(
            @RequestParam(required = false) Long examId,
            @RequestParam(required = false) Long classId,
            @RequestParam(required = false) String studentName
    ) {
        log.info("Searching grades with examId={}, classId={}, studentName={}", examId, classId, studentName);
        List<GradeDTO> grades = gradeService.searchGrades(examId, classId, studentName);
        return ResponseEntity.ok(grades);
    }

    @GetMapping("/stats")
    @ApiOperation(value = "获取学生成绩统计信息接口")
    public ResponseEntity<GradeStatsResponseDTO> gradeStats(@RequestParam Long studentId) { // 修改返回类型
        log.info("Getting grade stats for student with ID: {}", studentId);
        GradeStatsResponseDTO stats = gradeService.getStudentGradeStats(studentId);
        // 可以添加一个检查，如果stats中的studentName是"N/A"或特定错误标记，可能返回404
        // 但目前Service层会处理找不到学生的情况，并设置studentName为"N/A"
        return ResponseEntity.ok(stats);
    }
} 